package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类,定时处理订单状态
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     *  处理超时订单  状态改为 已取消
     *
     */
    @Scheduled(cron = "0 * * * * ? ")  //每分钟处理一次
    public void processTimeOrder(){
        log.info("超时自动取消订单：{}", LocalDateTime.now());

        //查询比当前时间减十五分钟早下单的订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,time);

        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("用户付款超时，自动取消");

                orderMapper.update(orders);
            }
        }
    }

    /**
     * 凌晨一点定时查询 一直处于在配送中的订单 并修改订单 改为 已完成
     */
    @Scheduled(cron = "0 0 1 * * ? ")  //每次凌晨一点触发
    public void processDeliveryOrder(){
        log.info("定时处理出于配送中的订单:{}",LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusHours(-1);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);

        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);

                orderMapper.update(orders);
            }
        }
    }


}
